// 文件上传错误过滤器

import { Catch, ExceptionFilter, ArgumentsHost, Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { FastifyReply } from 'fastify';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';

@Catch()
export class MultipartErrorFilter implements ExceptionFilter {
  constructor(
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
    private readonly configService: ConfigService,
  ) {}
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const reply = ctx.getResponse<FastifyReply>();
    const request: any = ctx.getRequest();
    const contentType = request.headers['content-type'] || '';
    const isMultipart = contentType.includes('multipart/form-data');
    if (isMultipart) {
      this.logger.error(exception?.code || exception?.message);
      if (
        exception?.name === 'RequestFileTooLargeError' ||
        exception?.code === 'FST_REQ_FILE_TOO_LARGE'
      ) {
        reply.status(413).send({
          code: 413,
          message: '文件大小超过限制',
          maxSize: `${this.configService.get('UPLOAD_SIZE_LIMIT')}KB`,
        });
      } else if (exception?.message === '文件类型不支持') {
        reply.status(415).send({
          code: 415,
          message: '文件类型不支持',
        });
      } else {
        reply.status(400).send({
          code: 400,
          message: '未检测到上传文件或没有新文件上传',
        });
      }
    } else {
      // 不是 multipart，抛回去让其他 filter 处理
      throw exception;
    }
  }
}
